package com.anysoft.user;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.anysoft.MentorConst;
import com.anysoft.utils.MentorLogger;
import com.blankj.utilcode.util.ToastUtils;
import com.anysoft.HostConstant;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.BaseBean;
import com.anysoft.bean.QueryBankInfoListBean;
import com.anysoft.bean.QueryBankTypeBean;
import com.anysoft.bean.QueryCertificateTypeBean;
import com.anysoft.bean.QuickAuthApplyBean;
import com.anysoft.bean.SmartCardBinByBankAccountNoBean;
import com.anysoft.event.IdentityCardEvent;
import com.anysoft.event.RegisterEvent;
import com.anysoft.event.RegisterSuccessEvent;
import com.anysoft.linstener.OnNextLinstener;
import com.anysoft.me.config.ServiceConfig;
import com.anysoft.me.utils.PermissionManager;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.ChinaPayUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.StringUtils;
import com.anysoft.view.picker.NomarlPickerPopupWindow;
import com.anysoft.web.MerChantsBankActivity;
import com.google.gson.Gson;
import com.hxcr.chinapay.activity.Initialize;
import com.hxcr.chinapay.util.CPGlobaInfo;
import com.hxcr.chinapay.util.Utils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.anysoft.MentorConst.FIRST_CUSTOMER;

/**
 * 找回密码
 */
public class RetrievePwdActivity extends BaseActivity implements PermissionManager.OnPermissionListener {

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.leftButton)
    Button leftButton;

    @BindView(R.id.et_user_name)
    EditText et_user_name;//真实姓名
    @BindView(R.id.tv_certificates_type)
    TextView tv_certificates_type;//证件类型
    @BindView(R.id.et_certificates_no)
    EditText et_certificates_no;//证件号码
    @BindView(R.id.et_bank_card_no_val)
    EditText et_bank_card_no_val;//银行卡号
    @BindView(R.id.et_bank_reserve_phone)
    EditText et_bank_reserve_phone;//预留手机号
    @BindView(R.id.rl_bank_card_ascription)
    RelativeLayout rl_bank_card_ascription;//归属银行

    //    @BindView(R.id.image_select_bank)
//    ImageView image_select_bank;//选择银行卡
    @BindView(R.id.tv_bank_card_name_val)
    TextView tv_bank_card_name_val;//归属银行名称
    @BindView(R.id.et_verification_code_val)
    EditText et_verification_code_val;//短信验证码
    @BindView(R.id.btn_get_verification_code)
    Button btn_get_verification_code;//获取短信验证码
    @BindView(R.id.btn_next)
    Button btn_next;//下一步
    @BindView(R.id.cbox_aggreement)
    CheckBox cbox_aggreement;//下一步
    @BindView(R.id.tv_jyxy)
    TextView tv_jyxy;//交易协议

    @BindView(R.id.iv_retrieve_identity_ocr)
    ImageView iv_retrieve_identity_ocr;//扫描身份证

    @BindView(R.id.iv_retrieve_bank_ocr)
    ImageView iv_retrieve_bank_ocr;//扫描银行卡

    /**
     * 证件类型列表
     */
    List<QueryCertificateTypeBean.DataBean> listIdType = new ArrayList<>();

    /**
     * 支持开户的银行
     */
    private List<QueryBankInfoListBean.DataBean> listBank = new ArrayList<>();

    private ArrayList<String> list = new ArrayList<String>();
    /**
     * 所选择的证件类型
     */
//    private String sSelectIdType;
//    /**
//     * 所选择银行-代码
//     */
//    private String sBankCode;

    private TimeCount time;
    /**
     * 是否在获取验证码中（60秒倒计时中）
     */
    private boolean getVerificationing = false;

    private boolean idTypePopShow = false;
    private boolean bankPopShow = false;
    private NomarlPickerPopupWindow nomarlPickerPopupWindow;
    private int selectPosition = -1;
    private int currentPosition;

    /**
     * 1.证件类型，2.归属银行
     */
    private int currentType = 1;

    private String sIdTypeCode;//所选择的证件类型编号
    private String sBankCode;//所选择归属银行编号

    /**
     * 鉴权申请号
     */
//    private String authApplyNo;
    private RegisterEvent saveRegisterEvent = new RegisterEvent();
    /**
     * 记录获取短信验证码的手机号
     */
    private String sMobileNo;
    /**
     * 鉴权申请返回数据
     */
    private QuickAuthApplyBean.DataBean currentDataBean;

    //是否是一类账户
    private boolean isFirstCus = false;
    private String trustChannelId = "";
    private boolean isScanIdResult = false;
    private boolean isScanBankResult = false;
    private String bankName;
    private String userName;
    private String certificates_no;
    private String bank_card_no_val;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrieve_pwd);
        ButterKnife.bind(this);
        title.setText("找回密码");
        listIdType = new ArrayList<>();
        cbox_aggreement.setChecked(true);
        time = new TimeCount(120 * 1000, 1000);
        btn_get_verification_code.setClickable(false);
        et_bank_reserve_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //输入文本之前的状态
                Logger.e("aaaaa", "beforeTextChanged=" + et_bank_reserve_phone.getText());
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //输入文字中的状态，count是一次性输入字符数
                Logger.e("aaaaa", "onTextChanged=" + et_bank_reserve_phone.getText());
                if (!getVerificationing) {
                    if (et_bank_reserve_phone.getText().length() == 11) {
                        btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_click_style);
                        btn_get_verification_code.setClickable(true);
                    } else {
                        btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_noclick_style);
                        btn_get_verification_code.setClickable(false);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                //输入文字后的状态
                Logger.e("aaaaa", "afterTextChanged=" + et_bank_reserve_phone.getText());
            }
        });

        et_bank_card_no_val.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    isScanBankResult = false;
                    if (!TextUtils.isEmpty(et_bank_reserve_phone.getText().toString().trim()) && isScanIdResult) {
                        isScanIdResult = false;
                    }
                } else {
                    if (!TextUtils.isEmpty(et_bank_card_no_val.getText().toString())) {
                        queryBankType();
                        queryCardBinByBankAccountNo();
                    }
                }
            }
        });


        et_verification_code_val.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                } else {
                    if (!TextUtils.isEmpty(et_bank_card_no_val.getText().toString())) {
                        queryBankType();
                    }
                }
            }
        });

        et_user_name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    isScanIdResult = false;
                    if (!TextUtils.isEmpty(et_bank_reserve_phone.getText().toString().trim()) && isScanBankResult) {
                        isScanBankResult = false;
                    }
                }
            }
        });

        et_certificates_no.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    isScanIdResult = false;
                    if (!TextUtils.isEmpty(et_bank_reserve_phone.getText().toString().trim()) && isScanBankResult) {
                        isScanBankResult = false;
                    }
                }
            }
        });
        setOnNextLinstener(new OnNextLinstener() {
            @Override
            public void OnCancelNext() {
                if (isScanIdResult || isScanBankResult) {
                    doVerificatioinCodeCheck();
                    isScanIdResult = false;
                    isScanBankResult = false;
                }
            }

            @Override
            public void OnConfirmNext() {
                et_certificates_no.clearFocus();
                et_user_name.clearFocus();
                et_bank_card_no_val.clearFocus();
            }

            @Override
            public void OndoConfirm() {

            }
        });
        getIdType();
        getBankList();
    }

    /**
     * 查询银行卡bin信息
     */
    public void queryBankType() {
        Map<String, String> params = new HashMap<>();
        params.put("bankNumber", et_bank_card_no_val.getText().toString());
        OkGo.<String>post(HostConstant.QUERY_BANK_TYPE)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        MentorLogger.LogJson(TAG + "查询银行卡是否为1类账户(允许开户)URL:", response.body());
                        UpdateQueryBankType(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }


    public void UpdateQueryBankType(String json) {

        QueryBankTypeBean bean;
        try {
            bean = new Gson().fromJson(json, QueryBankTypeBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        if (bean == null || bean.getData() == null || TextUtils.isEmpty(bean.getData().getOneAccount())) {
            showConfirmAlert(mActivity, "提示", getString(R.string.no_data));
            return;
        }

        if ("false".equals(bean.getData().getOneAccount())) {
            showConfirmAlert(mActivity, FIRST_CUSTOMER);
            isFirstCus = false;
        } else {
            isFirstCus = true;
        }
    }

    /**
     * 根据输入的银行卡号 查询 卡相关信息  卡bin
     */
    private void queryCardBinByBankAccountNo() {

        if (StringUtils.isNullOrEmpty(et_bank_card_no_val.getText().toString())) {
            return;
        }

        Map<String, String> params = new HashMap<>();

        if (checkParam(params, "bankAccountNo", et_bank_card_no_val.getText().toString(), "请输入银行卡号")) {
            return;
        }
        params.put("customerNo", getFundCustomerNo());
        OkGo.<String>post(HostConstant.QUERY_CARD_BIN_BY_BANK_ACCOUNT_NO)
                .tag(this)
                .upJson(new Gson().toJson(HttpUtils.getCommonParams(this, params)))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_CardBinInfo(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 解析鉴权申请接口返回的数据
     *
     * @param response
     */
    private void parseJson_CardBinInfo(String response) {
//        hideLoading();
        SmartCardBinByBankAccountNoBean bean;
        try {
            bean = new Gson().fromJson(response, SmartCardBinByBankAccountNoBean.class);
        } catch (Exception exception) {
            showConfirmAlert(this, "提示", "数据解析错误");
            return;
        }

        if (bean == null
                || TextUtils.isEmpty(bean.getErrorCode())) {
            showToast(MentorConst.SERVER_BUSY_TIP);
            return;
        }
        BaseBean baseBean = new BaseBean();
        baseBean.setRespCode(bean.getErrorCode());
        baseBean.setRespMsg(bean.getErrorMessage());
        if (!CommonUtil.checkState(this, baseBean, response)) {
            return;
        }

        if (bean == null || bean.getData() == null || bean.getData().getCardBin() == null || StringUtils.isNullOrEmpty(bean.getData().getCardBin().getBankNo())) {
            showConfirmAlert(this, "提示", "暂不支持此卡");
            return;
        }

        if (bean.getData().getSupportBankMap() != null) {
            for (QueryBankInfoListBean.DataBean beanBank : listBank) {
                if (beanBank.getBankCode().equals(bean.getData().getSupportBankMap().getBankCode())) {
                    bankName = beanBank.getBankName();
                    tv_bank_card_name_val.setText(bankName);
                    sBankCode = beanBank.getBankCode();
                    trustChannelId = beanBank.getTrustChannelId();
//                    currentCapitalMode = beanBank.getCapitalMode();
                    return;
                }
            }
        }

        showConfirmAlert(this, "提示", "暂不支持此卡");

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(Utils.getPayResult())) {
            String str = Utils.getPayResult();
            MentorLogger.Log(TAG, "银联返回数据：  " + str);
            String respCode = str.substring(10, 14);
            if (respCode.equals("0000")) {
                //TODO 是否还有接口要调取
                quickAuthConfirm();
            } else {
                showConfirmAlert(mActivity, "银联认证失败");
            }
            ChinaPayUtils.printChinapayResultCodeInfo(respCode);
        }
        CPGlobaInfo.init(); // 清空返回结果
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @OnClick({R.id.leftButton, R.id.btn_next, R.id.tv_certificates_type, R.id.rl_bank_card_ascription,
            R.id.btn_get_verification_code, R.id.iv_retrieve_identity_ocr, R.id.iv_retrieve_bank_ocr})
    public void onClick(View view) {
        if (!isFastDoubleClick()) {
            collapseSoftInputMethod(view.getWindowToken());
            if (et_bank_card_no_val.hasFocus() && !TextUtils.isEmpty(et_bank_card_no_val.getText().toString())) {
                queryBankType();
                queryCardBinByBankAccountNo();
            }
            iv_retrieve_identity_ocr.setClickable(true);
            switch (view.getId()) {
                case R.id.iv_retrieve_identity_ocr: //扫描身份证
                    if (TextUtils.isEmpty(sIdTypeCode)) {
                        showConfirmAlert(mActivity, "请选择证件类型");
                        return;
                    }
                    isIdentityClickable(sIdTypeCode);
                    if (!iv_retrieve_identity_ocr.isClickable()) {
                        showConfirmAlert(this, "目前只支持上传身份证");
                        return;
                    }
                    ActivityUtils.gotoUploadIditityCardActivity(this, sIdTypeCode, "3");
                    break;
                case R.id.iv_retrieve_bank_ocr: //扫描银行卡
                    requestIdentityPermissions();
                    break;
                case R.id.leftButton:
                    finish();
                    break;
                case R.id.btn_get_verification_code:
                    if (!dataCheck(1)) {
                        return;
                    }
                    if (isScanIdResult || isScanBankResult) {
                        showConfirmAlert(this, "提示", "请核对扫描结果,如有误请手动输入。\n\n姓名：" + userName
                                        + "\n证件号:" + certificates_no + "\n银行卡名称:" + bankName + "\n银行卡号: " + bank_card_no_val,
                                "有误,去修改", "无误,继续");
                    } else {
                        doVerificatioinCodeCheck();
                    }
                    break;

                case R.id.btn_next:
                    if (!dataCheck(2)) {
                        return;
                    }

                    if (listBank == null) {
                        showErrorMsg("请选择银行卡");
                        return;
                    }
//                    String currentCapitalMode="";
//                    String merId = "";
//                    for (QueryBankInfoListBean.DataBean beanBank : listBank) {
//                        if (beanBank.getBankCode().equals(sBankCode)) {
////                            currentCapitalMode = beanBank.getCapitalMode();
//                            merId = beanBank.getMerId();
//                            break;
//                        }
//                    }
                    if (!TextUtils.isEmpty(currentDataBean.getMerId())) {
                        //银联渠道
                        UpdateChinaPayAuth(currentDataBean);
                    } else {
                        quickAuthConfirm();
                    }
//                    if ("3".equals(currentCapitalMode)) {
//                        //银联渠道
//                        UpdateChinaPayAuth(currentDataBean);
//                    } else {
//                        quickAuthConfirm();
//                    }
//                    quickAuthConfirm();
                    break;
                case R.id.tv_certificates_type://证件类型选择
                    currentType = 1;

                    idTypePopShow = true;
                    currentPosition = 0;

                    initPopList();

                    if (list != null && !list.isEmpty() && list.size() > 0) {
                        showPicker();
                    } else {
                        getIdType();
                    }
                    break;
                case R.id.rl_bank_card_ascription://归属银行选择

                    currentType = 2;

                    bankPopShow = true;
                    currentPosition = 0;

                    initPopList();

                    if (list != null && !list.isEmpty() && list.size() > 0) {
                        showPicker();
                    } else {
                        getBankList();
                    }
                    break;
            }
        }
    }

    private void requestIdentityPermissions() {
        if (PermissionManager.getInstance().checkPermissions(this, PermissionManager.PERMISSION_READ_WEITE_CAMERA)) {
            ActivityUtils.openBankCardCamera(this);
        } else {
            PermissionManager.getInstance().requestPermissions(this, PermissionManager.REQUEST_READ_WEITE_CAMERA,
                    PermissionManager.PERMISSION_READ_WEITE_CAMERA, this);
        }
    }

    @Override
    public void onPermissionSuccess() {
        ActivityUtils.openBankCardCamera(this);
    }

    @Override
    public void onPermissionFail() {
        ToastUtils.showShort("请求权限失败,请重试");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void doVerificatioinCodeCheck() {

        if (et_bank_reserve_phone.getText().toString().length() == 11) {
//                        time.start();
            quickAuthApply();
        } else {
            showErrorMsg("手机号格式不对");
        }
    }

    /**
     * 判断扫描框是否可点击
     *
     * @param identityType
     */
    private void isIdentityClickable(String identityType) {
        if ("0".equals(identityType)) {
            iv_retrieve_identity_ocr.setClickable(true);
        } else {
            iv_retrieve_identity_ocr.setClickable(false);
        }
    }

    /**
     * @param checkType 1：鉴权 2：下一步（鉴权确认>修改密码）
     * @return
     */
    private boolean dataCheck(int checkType) {

        //真实姓名
        userName = et_user_name.getText().toString().trim();
        //证件号码
        certificates_no = et_certificates_no.getText().toString().trim();
        //银行卡号
        bank_card_no_val = et_bank_card_no_val.getText().toString().trim();
        String bank_reserve_phone = et_bank_reserve_phone.getText().toString().trim();//预留手机号
        String verification_code_val = et_verification_code_val.getText().toString().trim();//短信验证码
        if (StringUtils.isNullOrEmpty(userName)) {
            showErrorMsg("请输入真实姓名");
            return false;
        }
        if (sIdTypeCode == null || "".equals(sIdTypeCode)) {
            showErrorMsg("请选择证件类型");
            return false;
        }
        if (certificates_no == null || "".equals(certificates_no)) {
            showErrorMsg("请输入证件号码");
            return false;
        }
        if (sBankCode == null || "".equals(sBankCode)) {
            showErrorMsg("请选择银行卡");
            return false;
        }
        if (bank_card_no_val == null || "".equals(bank_card_no_val)) {
            showErrorMsg("请输入银行卡号");
            return false;
        }
        if (!isFirstCus) {
            showConfirmAlert(mActivity, FIRST_CUSTOMER);
            return false;
        }
        if (bank_reserve_phone == null || "".equals(bank_reserve_phone)) {
            showErrorMsg("请输入手机号");
            return false;
        }
        if (checkType == 2) {
            if (StringUtils.isNullOrEmpty(saveRegisterEvent.getMobilePhone())) {
                showErrorMsg("请先获取短信验证码");
                return false;
            }
            if (StringUtils.isNullOrEmpty(verification_code_val)) {
                showErrorMsg("请输入短信验证码");
                return false;
            }
        }
        if (!cbox_aggreement.isChecked()) {
            showErrorMsg("需要阅读并同意协议!");
            return false;

        }
        return true;
    }


    /**
     * 获取证件类型
     */
    private void getIdType() {
        OkGo.<String>post(HostConstant.QUERY_CERTIFICATE_TYPE)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, null))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJsonIdType(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private boolean isFirstComing = true;

    /**
     * 解析证件类型
     *
     * @param json
     */
    private void parseJsonIdType(String json) {

        listIdType.clear();
        list.clear();

        QueryCertificateTypeBean bean;
        try {
            bean = new Gson().fromJson(json, QueryCertificateTypeBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        if (bean == null || bean.getData() == null ||
                bean.getData().isEmpty() || bean.getData().size() < 1) {
            showConfirmAlert(mActivity, "提示", getString(R.string.no_data));
            return;
        }

        listIdType.addAll(bean.getData());
//        for (QueryCertificateTypeBean.DataBean dataBean : listIdType) {
//            list.add(dataBean.getTypeName());
//        }

        if (isFirstComing) {
            isFirstComing = false;
            sIdTypeCode = listIdType.get(0).getTypeValue();
            tv_certificates_type.setText(listIdType.get(0).getTypeName());
            isIdentityClickable(sIdTypeCode);
        }

        initPopList();
        if (idTypePopShow) {
            showPicker();
        }
    }

    private void showPicker() {
        nomarlPickerPopupWindow = new NomarlPickerPopupWindow(mActivity, itemsOnClick, list);
        nomarlPickerPopupWindow.showAtLocation(findViewById(R.id.activity_edit_user_pwd),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

        switch (currentType) {
            case 1:
                nomarlPickerPopupWindow.setTitle_str("请选择证件类型");
                break;
            case 2:
                nomarlPickerPopupWindow.setTitle_str("请选择银行卡");
                break;
            default:
                break;
        }

        nomarlPickerPopupWindow.setOnPickerChangeListener(
                new NomarlPickerPopupWindow.OnPickerChangeListener() {
                    @Override
                    public void onPickerChange(int position) {
                        currentPosition = position;
                    }
                });
    }

    private void initPopList() {
        list.clear();

        switch (currentType) {
            case 1:
                for (QueryCertificateTypeBean.DataBean dataBean : listIdType) {
                    list.add(dataBean.getTypeName());
                }
                break;
            case 2:
                for (QueryBankInfoListBean.DataBean dataBean : listBank) {
                    list.add(dataBean.getBankName());
                }
                break;
            default:
                break;
        }

    }

    /**
     * 获取支持开户的银行列表
     */
    private void getBankList() {
        Map<String, String> params = new HashMap<>();
        params.put("OpenAccountState", "1");
        OkGo.<String>post(HostConstant.QUERY_BANK_INFO_LIST)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_bank(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 解析服务端返回的数据--支持开户的银行
     *
     * @param json
     */
    private void parseJson_bank(String json) {
        listBank.clear();
        QueryBankInfoListBean bean;
        try {
            bean = new Gson().fromJson(json, QueryBankInfoListBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        if (bean == null || bean.getData() == null ||
                bean.getData().isEmpty() || bean.getData().size() < 1) {
            showConfirmAlert(mActivity, "提示", getString(R.string.no_data));
            return;
        }

        listBank.addAll(bean.getData());
        initPopList();

        if (bankPopShow) {
            showPicker();
        }
    }

    /**
     * 解析获取短信验证码返回的数据
     *
     * @param json
     */
    private void parseJson_sms_code(String json) {
        BaseBean bean;
        try {
            bean = new Gson().fromJson(json, BaseBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        if (bean == null) {
            showConfirmAlert(mActivity, "提示", getString(R.string.no_data));
            return;
        }
        showToast("验证码已发送请注意接收！");
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_noclick_style);
            btn_get_verification_code.setClickable(false);
            btn_get_verification_code.setText(millisUntilFinished / 1000 + "秒后重发");
            getVerificationing = true;
        }

        @Override
        public void onFinish() {
            btn_get_verification_code.setText("获取验证码");
            btn_get_verification_code.setClickable(true);
            btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_click_style);
            getVerificationing = false;

        }
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            nomarlPickerPopupWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_cancel:
                    if (nomarlPickerPopupWindow != null) {
                        nomarlPickerPopupWindow.dismiss();
                    }
                    break;
                case R.id.btn_sure:
                    if (nomarlPickerPopupWindow != null) {
                        selectPosition = currentPosition;
                        nomarlPickerPopupWindow.dismiss();

                        switch (currentType) {
                            case 1:
                                tv_certificates_type.setText(list.get(selectPosition));
                                sIdTypeCode = listIdType.get(selectPosition).getTypeValue();
                                break;
                            case 2:
                                bankName = listBank.get(selectPosition).getBankName();
                                tv_bank_card_name_val.setText(bankName);
                                sBankCode = listBank.get(selectPosition).getBankCode();
                                trustChannelId = listBank.get(selectPosition).getTrustChannelId();
                                isScanBankResult = false;
                                if (!TextUtils.isEmpty(sMobileNo) && isScanIdResult) {
                                    isScanIdResult = false;
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 鉴权接口
     */
    private void quickAuthApply() {
        Map<String, String> params = new HashMap<>();

        userName = et_user_name.getText().toString().trim();//真实姓名
        certificates_no = et_certificates_no.getText().toString().trim();//证件号码
        bank_card_no_val = et_bank_card_no_val.getText().toString().trim();//银行卡号
        sMobileNo = et_bank_reserve_phone.getText().toString().trim();//预留手机号
        if (listBank == null) {
            showErrorMsg("请选择银行卡");

            return;
        }
        saveRegisterEvent.setUsername(userName);
        saveRegisterEvent.setIdentityType(sIdTypeCode);
        saveRegisterEvent.setIdentityNo(certificates_no);
        saveRegisterEvent.setBankCode(sBankCode);
        saveRegisterEvent.setBankAccountNo(bank_card_no_val);
//        saveRegisterEvent.setMobilePhone(bank_reserve_phone);
        params.put("bankCode", sBankCode);//银行代码
        params.put("bankName", bankName);//银行名称
        params.put("bankAccountNo", bank_card_no_val);//银行账号
        params.put("username", userName);//投资人姓名
        params.put("identityType", sIdTypeCode);//证件类型
        params.put("identityNo", certificates_no);//证件号码
        params.put("mobilePhone", sMobileNo);//手机号码
        params.put("authType", "1");//鉴权类型		M	0-开户鉴权，1-找回密码鉴权
        params.put("trustChannelId", "" + trustChannelId);//交易渠道
        params.put("operationType", "1");//0-开户 1-忘记密码  2-加卡
        setVerificationCodeStatuts(false);
        OkGo.<String>post(HostConstant.QUICK_AUTH_APPLY)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_QuickAuth(1, response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        setVerificationCodeStatuts(true);
                        showErrorMsg("验证码获取失败");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 鉴权确认
     */
    private void quickAuthConfirm() {
        if (!et_bank_card_no_val.getText().toString().equals(saveRegisterEvent.getBankAccountNo()) ||
                !et_user_name.getText().toString().trim().equals(saveRegisterEvent.getUsername()) ||
                !et_bank_reserve_phone.getText().toString().equals(saveRegisterEvent.getMobilePhone()) ||
                !et_certificates_no.getText().toString().equals(saveRegisterEvent.getIdentityNo()) ||
                !sIdTypeCode.equals(saveRegisterEvent.getIdentityType()) ||
                !sBankCode.equals(saveRegisterEvent.getBankCode())
                ) {

            showConfirmAlert(mActivity, "您修改了个人信息，请重新获取验证码");
            return;
        }

        Map<String, String> params = new HashMap<>();
        String verification_code_val = et_verification_code_val.getText().toString().trim();//短信验证码

        if (checkParam(params, "authApplyNo", saveRegisterEvent.getAuthApplyNo(), "请先获取短信验证码")) {
            return;
        }
        if (checkParam(params, "verifyCode", et_verification_code_val.getText().toString(), "请输入短信验证码")) {
            return;
        }
        setBtnNextStatuts(false);
        OkGo.<String>post(HostConstant.QUICK_AUTH_CONFIRM)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_QuickAuth(2, response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        setBtnNextStatuts(true);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 解析鉴权申请接口返回的数据
     *
     * @param type     1.鉴权申请 2.鉴权确认
     * @param response
     */
    private void parseJson_QuickAuth(int type, String response) {
        QuickAuthApplyBean bean;
        try {
            bean = new Gson().fromJson(response, QuickAuthApplyBean.class);
        } catch (Exception exception) {
            showConfirmAlert(this, "提示", "数据解析错误");
            if (type == 1) {
                setVerificationCodeStatuts(true);
//                time.cancel();
//                time.onFinish();
            }
            if (type == 2) {
                setBtnNextStatuts(true);
            }
            return;
        }

        if (!CommonUtil.checkState(this, bean, response)) {
            if (type == 1) {
//                time.cancel();
//                time.onFinish();
                setVerificationCodeStatuts(true);
            }
            if (type == 2) {
                setBtnNextStatuts(true);
            }
            return;
        }

        if (bean == null || bean.getData() == null) {
            showConfirmAlert(this, "提示", getString(R.string.no_data));
            if (type == 1) {
                setVerificationCodeStatuts(true);
//                time.cancel();
//                time.onFinish();
            }
            if (type == 2) {
                setBtnNextStatuts(true);
            }
            return;
        }
        switch (type) {
            case 1:
                setVerificationCodeStatuts(true);
                time.start();
                currentDataBean = bean.getData();
                saveRegisterEvent.setMobilePhone(sMobileNo);
                saveRegisterEvent.setAuthApplyNo(bean.getData().getAuthApplyNo());
                break;
            case 2:
                if (listBank == null) {
                    showErrorMsg("请选择银行卡");
                    return;
                }
                saveRegisterEvent.setTrustChannelId(trustChannelId);
                QuickAuthApplyBean.DataBean authDataBean = bean.getData();
                saveRegisterEvent.setAuthApplyNo(authDataBean.getAuthApplyNo());
                Intent intent = null;
                if ("H5".equals(authDataBean.getAuthMethod())) {
                    intent = new Intent().setClass(mActivity, MerChantsBankActivity.class);
                    intent.putExtra("formContent", authDataBean.getFormContent());
                    intent.putExtra("returnUrl", authDataBean.getReturnUrl());
                    startActivityForResult(intent, HostConstant.START_CHANTS_BANK);
                } else {
                    gotoNextPage();
                }
                break;
            default:
                break;
        }

    }

    private void gotoNextPage() {
        Intent intent;
        intent = new Intent().setClass(mActivity, RetrievePwdEditActivity.class);
        intent.putExtra("retrievePwdEvent", saveRegisterEvent);
        startActivity(intent);
    }

    /**
     * 银联插件报文获取
     *
     * @param bean
     */
    private void UpdateChinaPayAuth(QuickAuthApplyBean.DataBean bean) {
        Utils.setPackageName(getPackageName());
        String xml = ChinaPayUtils.getXml(ServiceConfig.CHINA_PAY_ENVIRONMENT, bean.getMerId(), bean.getMerOrderId(),
                bean.getMerOrderTime(), bean.getCharacterCode(), bean.getSign());

        // 调用银行插件进行开户，在此类的onResume()方法中获取插件的返回结果
        Intent inten = new Intent(this, Initialize.class);
        inten.putExtra(CPGlobaInfo.XML_TAG, xml);
        startActivity(inten);
    }


    private void setVerificationCodeStatuts(boolean isOpen) {
        if (isOpen) {
            if (et_bank_reserve_phone.getText().toString().length() < 11) {
                btn_get_verification_code.setText("获取验证码");
                btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_noclick_style);
                btn_get_verification_code.setClickable(false);
            } else {
                btn_get_verification_code.setText("获取验证码");
                btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_click_style);
                btn_get_verification_code.setClickable(true);
            }

        } else {
            btn_get_verification_code.setText("获取验证码");
            btn_get_verification_code.setBackgroundResource(R.drawable.get_verification_noclick_style);
            btn_get_verification_code.setClickable(false);

        }
    }


    private void setBtnNextStatuts(boolean isOpen) {
        if (isOpen) {
            btn_next.setBackgroundResource(R.drawable.get_verification_click_style);
            btn_next.setClickable(true);

        } else {
            btn_next.setBackgroundResource(R.drawable.get_verification_noclick_style);
            btn_next.setClickable(false);

        }
    }

    private void showErrorMsg(String msg) {
        if (msg == null || "".equals(msg.trim())) {
            return;
        }
        showConfirmAlert(mActivity, msg + "");
//        showToast(msg);
//        tv_error_msg.setText(msg);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == HostConstant.STRAT_UPLOAD_ID && resultCode == HostConstant.RESULT_UPLOAD_ID) {
            String name = data.getStringExtra("name");
            String id_number = data.getStringExtra("id_number");
            et_user_name.setText(name);
            et_certificates_no.setText(id_number);
        } else if (requestCode == HostConstant.START_BANK_CARD && resultCode == HostConstant.RESULT_BANK_CARD) {
            isScanBankResult = true;
            bank_card_no_val = data.getStringExtra("CardNum").replace(" ", "");
            et_bank_card_no_val.setText(bank_card_no_val);
            et_bank_card_no_val.clearFocus();
            queryBankType();
            queryCardBinByBankAccountNo();
        } else if (requestCode == HostConstant.START_CHANTS_BANK && resultCode == HostConstant.RESULT_CHANTS_BANK) {
            String status = data.getStringExtra("status");
            if ("Y".equals(status)) {
                gotoNextPage();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onIdentityCardEvent(IdentityCardEvent event) {
        isScanIdResult = true;
        userName = event.id_name;
        certificates_no = event.id_number;
        et_user_name.setText(event.id_name);
        et_certificates_no.setText(event.id_number);
        et_user_name.clearFocus();
        et_certificates_no.clearFocus();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGestureSetCallBack(RegisterSuccessEvent event) {
        if (event.isSuccess) {
            finish();
        }
    }
}
